<?php

class AlbumController extends Controller
{
	public $layout='//layouts/user_main';

	public function filters()
	{
		return array(
				'accessControl',
		);
	}

	public function accessRules()
	{
		return array(
				array("allow",
						'actions'=>array('upload','delete'),
						'users'=>array('@')
				),
				array('allow',
						'actions'=>array('admin'),
						'users'=>array('admin'),
				),
				array('deny',
						'users'=>array('*'),
				),
		);
	}

	public function actionUpload($album_id){
		if(isset($_FILES['uploadImages'])){
			foreach ($_FILES['uploadImages']['name'] as $imageIndex => $imageName) {
				$image = new Image();
				$image->album_id = $_GET['album_id'];
				$image->member_id = Yii::app()->user->id;
				$image->save();
				$file = Utils::getImagePathById("album", "", $image->id);
				$file_thumbnail = Utils::getImagePathById("album", "thumbnail", $image->id);
				$image_file=CUploadedFile::getInstanceByName("uploadImages[$imageIndex]");
				if(empty($image_file)){
					$image->delete();
					continue;
				}
				$image_file->saveAs($file);
				ImageUtils::resize($file,$file ,800 ,800,false );
				ImageUtils::resize($file,$file_thumbnail ,100 ,100,true );
			}
		}
		if(isset($_POST['deleteImages'])){
			foreach ($_POST['deleteImages'] as $imageId){
				$image = Image::model()->findByPk($imageId);
				$image->delete();
				$file = Utils::getImagePathById("album", "", $image->id);
				$file_thumbnail = Utils::getImagePathById("album", "thumbnail", $image->id);
				@unlink($file);
				@unlink($file_thumbnail);
			}
		}
		$images = Image::model()->findAll("album_id = :album_id",array("album_id"=>$album_id));
		$this->render("upload",array(
				'album'=>Album::model()->findByPk($album_id),
				"images"=>$images
		));
	}
}
